﻿#include "taskinfosql.h"

#include "componentmanager.h"
#include "component_log.h"
#include "json_trans.h"
#include "sql\sql_data.h"

TaskInfoSql::TaskInfoSql()
{}

TaskInfoSql::~TaskInfoSql()
{}



bool TaskInfoSql::Init()
{
	// 获取数据库组件实例
	m_db = component->GetComponent(Component::component_sql);
	if (m_db == nullptr) {
		log_error("load sql component failed");
		return false;
	}

	// 订阅wcsmsg组件的任务消息
	auto wcs = component->GetComponent(Component::component_wcsSend);
	if (wcs == nullptr) {
		log_error("load wcs send component failed");
		return false;
	}
	bool ret = wcs->RegisterSubscriberFunction((int)WCSendType::wcs_send_taskfinish, [&](const QByteArray& task) {
		return this->OnTaskFinished(task);
		});
	if (!ret) {
		log_error("register callback failed");
		return false;
	}
	QByteArray output = {};
	ret = m_db->ExcuteCmd((int)SqlCmdType::sql_create_table, m_tableName.toUtf8(), output);
	if (!ret) {
		log_error("db add tab failed");
		return false;
	}
	return true;
}

json_struct(TaskSqlInfo,
	mapping(QString, taskId);
mapping(int, stackFinish);
prop(&taskId, &stackFinish)
)

bool TaskInfoSql::InsertTask(const QByteArray& data)
{
	TaskSqlInfo info = {};
	info.fromJson(data);
	int id = info.taskId().toInt();
	if (id == 0) {
		id = (int)info.taskId().toStdString().at(0);
	}
	SqlWriteIn input = {};
	input.table = m_tableName;
	input.id = id;
	input.data = data;
	QByteArray output;
	log_trace("insert task {} to sql", info.taskId());
	m_taskList.append(info.taskId());
	return m_db->ExcuteCmd((int)SqlCmdType::sql_add_data, input.toByteArray(), output);
}

bool TaskInfoSql::ReadAllTask(QByteArrayList& tasks)
{
	SqlReadIn input = {};
	input.table = m_tableName;
	input.id = -1;
	QByteArray output = {};
	if (m_db->ExcuteCmd((int)SqlCmdType::sql_read_data, input.toByteArray(), output)) {
		SqlReadOut result = {};
		result.fromJson(output);
		for (auto& iter : result.data()) {
			tasks.append(iter.toUtf8());
		}
		return true;
	}

	return false;
}

bool TaskInfoSql::DeleteTask(const QString& taskId)
{
	int id = taskId.toInt();
	if (id == 0) {
		id = (int)taskId.toStdString().at(0);
	}
	SqlReadIn input = {};
	input.table = m_tableName;
	input.id = id;
	QByteArray output;
	log_trace("delete task {} to sql", taskId);
	
	for (int i = 0; i < m_taskList.size(); i++) {
		if (m_taskList.at(i) == taskId) {
			m_taskList.removeAt(i);
			break;
		}	
	}

	return m_db->ExcuteCmd((int)SqlCmdType::sql_delete_data, input.toByteArray(), output);
}

int TaskInfoSql::OnTaskFinished(const QByteArray& data)
{
	TaskSqlInfo info = {};
	info.fromJson(data);

	int id = info.taskId().toInt();
	if (id == 0) {
		id = (int)info.taskId().toStdString().at(0);
	}
	SqlReadIn input = {};
	input.table = m_tableName;
	input.id = id;
	QByteArray output;
	log_trace("delete task {} to sql", info.taskId());
	m_db->ExcuteCmd((int)SqlCmdType::sql_delete_data, input.toByteArray(), output);
	return 0;
}

QStringList TaskInfoSql::GetTaskList()
{
	return m_taskList;
}
